const path = require('path')
const fs = require('fs')
const dotEnv = require('dotenv')
const minimist = require('minimist')

const createEnvJs = () => {
  const args = minimist(process.argv.slice(2))
  const mode = args.mode || 'production'
  // 绝对路径
  const appDirectory = fs.realpathSync(process.cwd())

  const modeEnvPath = path.join(appDirectory, `.env.${mode}`)
  if (!fs.existsSync(modeEnvPath)) {
    console.log(`未找到.env.${mode}文件`)
    process.exit(1)
    return
  }
  const modeEnvBuffer = fs.readFileSync(modeEnvPath)
  const modeEnvConfig = dotEnv.parse(modeEnvBuffer)

  const envPath = path.join(appDirectory, '.env')
  let envConfig = {}
  if (fs.existsSync(envPath)) {
    const envBuffer = fs.readFileSync(envPath)
    envConfig = dotEnv.parse(envBuffer)
  }
  const config = {
    ...envConfig,
    ...modeEnvConfig
  }
  // 将内容写入到对应的js文件中
  const data = `window.env = ${JSON.stringify(config, null, 2)}`
  const distPath = path.join(appDirectory, 'dist')
  const distEnvPath = path.join(distPath, 'env')
  if (!fs.existsSync(distEnvPath)) {
    fs.mkdirSync(distEnvPath)
  }
  // 移除developmentjs
  fs.unlinkSync(path.join(distEnvPath, `env.development.js`))
  fs.writeFileSync(path.join(distEnvPath, `env.production.js`), data, 'utf-8')

  fs.renameSync(distPath, path.join(appDirectory, 'vlbodweb'))
}

createEnvJs()
